package org.pim.smart.service;

import java.util.Collections;
import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.pim.smart.hibernate.domain.GroupContact;
import org.pim.smart.hibernate.domain.GroupContactDAO;

public class GroupContactServiceImpl implements GroupContactService {
	
	private GroupContactDAO groupDao;

	public GroupContactServiceImpl(){
		groupDao = new GroupContactDAO();
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public List<GroupContact> getGroupsByUserId(Integer userId) {
		// TODO Auto-generated method stub
		Transaction tx = null;
		List<GroupContact> result = null;
		try {
			Session session = groupDao.getSession();
			tx = session.beginTransaction();
			Query query = session.createQuery("from " + GroupContact.class.getName() + " as gc where gc.sysUser="+userId.toString() + "order by gc.groupOid asc");
			result = query.list();
		} catch (HibernateException e){
			if (tx != null){
				tx.rollback();
			}
			e.printStackTrace();
		}
		if (result == null){
			return Collections.EMPTY_LIST;
		} else {
			return result;
		}
	}

	@Override
	public void releaseDataBaseResource() {
		// TODO Auto-generated method stub
		if (groupDao != null){
			groupDao.getSession().close();
		}
	}

}
